<template>
  <page-layout>
    <div slot="toolbar">
      <el-button size="small" round type="primary"  @click="newRole">新增职位</el-button>
      <el-button size="small" round type="primary" @click="newAdmin">新增管理员</el-button>
      <el-button size="small" round type="primary" v-has="{class:'Permission:addMenu'}" @click="addMenu" >新增菜单</el-button>
    </div>
    <div class="card-header">职位管理</div>
    <el-card class="box-card mb20">
      <div class="flex-row">
        <div class="flex-item-fixed mr10">
          <el-table
            :data="roleList" border stripe
            highlight-current-row
            @current-change="selectRole" row-class-name="link" style="width:281px" ref="roles">
            <el-table-column
              prop="roleName"
              label="职位名称"
              width="280">
              <template slot-scope="scope">
                <span>{{scope.row.roleName}}</span>
                <el-tag type="danger" size="small" style="float: right" v-if="scope.row.status==='unsave'">未保存</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex-item">
          <el-card>
            <el-form ref="form" :model="currentRole" label-width="80px" v-if="currentRole !== null">
              <el-form-item label="职位名称" prop="roleName" :rules="[
              { required: true, message: '请填写角色名称', trigger: 'change,blur' }
              ]">
                <el-input v-model="currentRole.roleName"></el-input>
              </el-form-item>
              <el-form-item label="可用菜单" prop="menusIds">
                <el-tree node-key="id"
                         :data="allMenus"
                         :default-checked-keys="currentRole.menusIds"
                         show-checkbox
                         default-expand-all
                         ref="tree"
                         check-strictly
                         @node-click="editMenu"
                         :props="treeProps" @check-change="powerChange">

                </el-tree>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="currentRole.remarks"  type="textarea"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" @click="saveRole">保存</el-button>
                <el-button type="danger" size="mini" @click="deleteRole">删除</el-button>
                <el-button size="mini" @click="cancel">取消</el-button>
              </el-form-item>
            </el-form>
            <el-alert
              title="选择要管理的职位"
              type="warning" :closable="false" show-icon v-else>
            </el-alert>
            <!--<el-button @click="addMenu">新增菜单</el-button>-->
          </el-card>
        </div>
      </div>
    </el-card>

    <div class="card-header">管理员授权</div>
    <el-card class="box-card">
      <el-table
        :data="admins.content" border stripe
        style="width: 100%">
        <el-table-column
          prop="id"
          label="编号"
          width="55">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="150"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号" width="150">
        </el-table-column>
        <el-table-column
          prop="areaName"
          label="区域" width="150">
        </el-table-column>
        <el-table-column label="当前职位">
          <template slot-scope="scope">
            {{getAdminRole(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" @click="editAdmin(scope.$index, scope.row)" type="text">编辑</el-button>
            <el-button size="mini" type="text" v-if="scope.row.username!=='admin'" @click="assignRole(scope.row)">分配职位</el-button>
            <el-button size="mini" type="text" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button style="color: #f43838;" size="mini" type="text" v-if="scope.row.username!=='admin'" @click="delAdmin(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="admins.totalElements"
          :page-size="admins.size"
          :current-page.sync="currentAdminPage" @current-change="adminPageChange">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog :visible.sync="showAdminEditor" title="添加/编辑 管理员" width="80%">
      <admin-editor @close="onAdminEditorClose" :is-close="showAdminEditor"></admin-editor>
    </el-dialog>

    <el-dialog title="分配职位" :visible.sync="showRoleSetting" width="70%" >
      <el-checkbox-group v-model="selectedRole" size="medium">
        <el-checkbox v-for="(role,index) in roleList" :label="role.id" :key="index" @change="checkRole(role)" border
                     size="medium">{{role.roleName}}
        </el-checkbox>
      </el-checkbox-group>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="showResetPwd" width="500px">
      <el-form ref="form" :rules="passRules" :model="resetUserPasswordForm" label-width="80px" class="demo-form">
        <el-form-item label="密码" prop="password">
          <el-input v-model="resetUserPasswordForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPwdCommit('form')">重置</el-button>
          <el-button @click="resetPwdCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="showMenuEditor" title="添加/编辑 菜单" width="80%">
      <menu-editor @close="onMenuEditorClose" :is-close="showMenuEditor"></menu-editor>
    </el-dialog>

  </page-layout>
</template>
<script>
import PageLayout from "@/components/page-layout";
import AdminEditor from "./admin-editor";
import MenuEditor from "./menu-editor";
import { mapGetters } from "vuex";
import md5 from "js-md5";
export default {
  created() {
    this.$store.dispatch("getRoles").then(ret => {});
    this.$store.dispatch("getAllMenus").then(ret => {});
    this.$store.dispatch("getMenuIDTree").then(ret => {});
    this.$store
      .dispatch("getAdminUserPageS", { pageIndex: 0, pageSize: 10 })
      .then(ret => {});
    this.$store
      .dispatch("getAreasS", { recursion: false, code: "410300" })
      .then(res => {});
  },
  mounted() {},
  data() {
    return {
      currentAdminPage: 1,
      treeProps: {
        children: "children",
        label: "menuName",
        admins: "admins"
      },
      showAdminEditor: false,
      showRoleSetting: false,
      showResetPwd: false,
      showMenuEditor: false,
      selectedUser: {},
      selectedRole: [],
      resetUserPasswordForm: {
        password: ""
      },
      passRules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 8, max: 15, message: "长度在 8 到 15 个字符", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      allMenus: "allMenus",
      roleList: "roleList",
      adminInfo: "adminInfo",
      currentRole: "currentRole",
      admins: "admins"
    })
  },
  methods: {
    adminPageChange(val) {
      this.$store
        .dispatch("getAdminUserPageS", {
          pageIndex: val - 1,
          userRole: "Admin"
        })
        .then(ret => {});
    },
    addMenu() {
      this.$store.commit("INIT_CURRENT_MENU");
      this.showMenuEditor = true;
    },
    editMenu(data) {
      this.$store.dispatch("getOneMenuS", data).then(ret => {});
      this.showMenuEditor = true;
    },
    selectRole(val) {
      this.$nextTick(() => {
        if (val) {
          this.$store.dispatch("initCurrentRole", val).then(ret => {
            console.log(val, val.menusIds, 333);
            this.$refs.tree.setCheckedKeys(val.menusIds);
            this.$store.dispatch("updateCurrentRole", val).then(ret => {});
          });
        }
      });
    },
    saveRole() {
      this.currentRole.menusIds = this.$refs.tree.getCheckedKeys();
      this.currentRole.menus = [];
      if (this.currentRole.menusIds) {
        this.currentRole.menusIds.map((item, index) => {
          this.currentRole.menus.push({ menuId: item });
        });
      }

      console.log(this.currentRole, 88);
      this.$store.dispatch("saveRole", this.currentRole).then(ret => {
        this.currentRole.id = ret.data.data.id;
        this.currentRole.status = "saved";
        this.$store
          .dispatch("updateCurrentRole", this.currentRole)
          .then(ret => {});
        this.$store.dispatch("getRoles").then(ret => {});
        console.log(this.roleList, 444);
        this.$notify({
          title: "保存成功",
          type: "success"
        });
      });
    },
    deleteRole() {
      if (this.currentRole.status === "unsave") {
        const currentIndex = this.roleList.findIndex(
          item => item._tmp_key === this.currentRole._tmp_key
        );
        this.roleList.splice(currentIndex, 1);
      } else {
        this.$confirm("确认删除该职位吗?", "提示", {})
          .then(() => {
            this.$store
              .dispatch("delRole", { roleId: this.currentRole.id })
              .then(ret => {
                // console.log("del:", ret);
                this.$store.dispatch("getRoles").then(ret => {});
                this.cancel();
                this.$notify({
                  title: "删除成功",
                  type: "success"
                });
              });
          })
          .catch(() => {});
      }
    },
    cancel() {
      this.$store.commit("RESET_CURRENT_ROLE");
      // this.$refs.roles.setCurrentRow(null);
    },
    //删除管理员
    delAdmin(row) {
      this.$confirm("确认删除当前管理员吗?", "提示", {})
        .then(() => {
          this.$store.dispatch("deleteAdminUserS", { id: row.id }).then(ret => {
            this.adminPageChange(1);
            this.$notify({
              title: "删除成功",
              type: "success"
            });
          });
        })
        .catch(() => {});
    },
    newRole() {
      this.$store.commit("CREATE_ROLE");
      this.$store.commit("INIT_CURRENT_ROLE");
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.roles.setCurrentRow(this.roleList[this.roleList.length - 1]);
      });
    },
    powerChange(obj) {
      this.currentRole.menusIds = this.$refs.tree.getCheckedKeys();
    },
    newAdmin() {
      this.$store.commit("INIT_CURRENT_ADMIN");
      this.showAdminEditor = true;
    },
    editAdmin(index, row) {
      // this.$store.commit("UPDATE_CURRENT_ADMIN", row);
      console.log(row);
      this.$store.dispatch("getAdminUserS", { id: row.id });
      this.showAdminEditor = true;
    },
    assignRole(user) {
      this.selectedRole = [];
      user.roles.forEach(item => {
        this.selectedRole.push(item.id);
      });
      this.showRoleSetting = true;
      this.selectedUser = user;
    },
    checkRole(val) {
      const ret = this.selectedRole.indexOf(val.id);
      if (ret === -1) {
        // 删除
        this.$store
          .dispatch("deleteUserRole", {
            userId: this.selectedUser.id,
            roleId: val.id
          })
          .then(ret => {
            this.$notify({
              title: "操作成功",
              type: "success"
            });
            this.onAdminEditorClose();
          });
      } else {
        this.$store
          .dispatch("addUserRole", {
            userId: this.selectedUser.id,
            roleId: val.id
          })
          .then(ret => {
            this.$notify({
              title: "操作成功",
              type: "success"
            });
            this.onAdminEditorClose();
          });
      }
    },
    resetPwd(user) {
      this.showResetPwd = true;
      this.selectedUser = user;
      this.resetUserPasswordForm.password = "";
    },
    resetPwdCommit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const payload = {
            userId: this.selectedUser.id,
            password: md5(this.resetUserPasswordForm.password)
          };

          this.$store.dispatch("resetAdminPassowrd", payload).then(ret => {
            this.$notify({
              title: "操作成功",
              type: "success"
            });
            this.showResetPwd = false;
          });
        } else {
          return false;
        }
      });
    },
    resetPwdCancel() {
      this.showResetPwd = false;
    },
    onAdminEditorClose() {
      this.showAdminEditor = false;
      this.adminPageChange(1);
    },
    onMenuEditorClose() {
      this.showMenuEditor = false;
      this.$store.dispatch("getAllMenus").then(ret => {});
    },
    getAdminRole(user) {
      return user.roles.reduce(
        (pre, cur) => {
          return { roleName: `${pre.roleName} ${cur.roleName}` };
        },
        { roleName: "" }
      ).roleName;
    }
  },
  components: {
    PageLayout,
    AdminEditor,
    MenuEditor
  }
};
</script>
<style>
</style>
